package com.woniu.car.config;

import com.woniu.car.realm.ShiroRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public CredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        // 加密算法
        matcher.setHashAlgorithmName("md5");
        // 迭代次数
        matcher.setHashIterations(3);
        return matcher;
    }
    /**
     * 01 配置 自定义的reaml
     */
    @Bean
    public ShiroRealm shiroRealm(CredentialsMatcher credentialsMatcher) {
        ShiroRealm shiroRealm = new ShiroRealm();
        shiroRealm.setCredentialsMatcher(credentialsMatcher);
        return shiroRealm;
    }

    /**
     * 02 配置securityManager
     * SecurityManager 这是接口
     * 有很多实现类:
     * springboot中需要使用的是:
     * DefaultWebSecurityManager( web安全管理器 )
     */
    @Bean
    public SecurityManager securityManager(ShiroRealm shiroRealm) {

        SecurityManager securityManager  =new DefaultWebSecurityManager(shiroRealm);
        return securityManager;
    }

    /**
     * 配置 shirofilter ?
     * shiro考虑到需要配置filter (和mybatis的思想一致 需要配置 shiroFilterFactoryBean)
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        factoryBean.setSecurityManager(securityManager);

        //登录页面的配置
//        factoryBean.setLoginUrl("/login");

        //认证失败的页面 (认证失败后跳转的页面)
//        factoryBean.setUnauthorizedUrl("/unauthorizedUrl.html");

        //其他的资源操作? 需要拦截

        Map<String,String> filterChainMap = new HashMap<>();

        //key 是请求url    value 拦截器
        // anon     不用拦截的 过滤器
        filterChainMap.put("/login","anon");
//        filterChainMap.put("/register","anon");

        //不用认证可以访问
//        filterChainMap.put("/index.html","anon");
//        filterChainMap.put("/login.html","anon");
//        filterChainMap.put("/register.html","anon");

        //其他的所有的资源都需要拦截
        // authc 认证过滤器； 访问/**所有资源都需要认证，除了放行的。
//        filterChainMap.put("/**","authc");

        //配置拦截的过滤器
        factoryBean.setFilterChainDefinitionMap(filterChainMap);

        return factoryBean;
    }
}
